<template>
  <div class="container">
    <OrderBar :order="serviceNo" :username="userInfo.userName"></OrderBar>
    <div class="content">
      <van-form ref="form" class="form">
        <van-cell title="其他费用">
          <van-icon
            name="add-o"
            color="blue"
            size="18"
            @click="addOtherCost"
          />
        </van-cell>
        <div v-for="(v, i) in form.otherCost" :key="v.time" class="otherCost van-cell">
          <div class="left">
            <div class="van-cell">
              <van-field
                v-model="v.workDay"
                readonly
                required
                :name="`otherCost.${i}.workDay`"
                :rules="rules.required"
                clickable
                label=""
                placeholder="费用日期"
                @click="openCalendar('workDay', v)"
              />
            </div>
            <div class="van-cell">
              <van-field
                v-model="v.feePurposeName"
                required
                readonly
                :name="`otherCost.${i}.feePurpose`"
                :rules="rules.required"
                clickable
                placeholder="费用属性"
                @click="openPicker('feePurpose', v, changeCost)"
              />
              <van-field
                v-model="v.feeNum"
                type="number"
                required
                :name="`otherCost.${i}.feeNum`"
                :rules="rules.required"
                placeholder="数量"
                label-width="40px"
              />
              <van-field
                v-model="v.price"
                type="number"
                required
                :disabled="!!moneyMap[v.feePurpose]"
                :name="`otherCost.${i}.price`"
                :rules="rules.required"
                placeholder="价格"
                label-width="40px"
              />
            </div>
            <div>
              <van-field
                v-model="v.feeDesc"
                rows="1"
                autosize
                required
                :name="`otherCost.${i}.feeDesc`"
                :rules="rules.required"
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="花费内容"
              />
            </div>
          </div>
          <div class="right">
            <van-icon
              name="close"
              color="red"
              size="18"
              @click="removeOtherCost(i)"
            />
          </div>

        </div>

        <van-calendar
          v-model="showCalendar"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirmCalendar"
        />

        <van-popup
          v-model="showPicker"
          position="bottom"
        >
          <van-picker
            show-toolbar
            :columns="currentOptions"
            value-key="label"
            @confirm="onConfirmPicker"
            @cancel="showPicker = false"
          >
            <van-search
              v-if="currentOptionsCache.length>showSearchMaxOptionsLength"
              slot="title"
              v-model="pickerKeyword"
              placeholder="快速搜索"
              shape="round"
              @input="filterCurrentOptions"
            />
          </van-picker>
        </van-popup>

        <div class="btns">
          <van-button
            type="warning"
            size="small"
            icon="checked"
            @click="submit('/saleService/batchSaveOrUpdateSaleServiceFee?saleServiceId='+form.saleServiceId)"
          >提交
          </van-button>
          <van-button
            type="danger"
            size="small"
            icon="clear"
            @click="close"
          >关闭
          </van-button>
        </div>
      </van-form>
    </div>
    <!--    <div v-else class="nodata">-->
    <!--      <img src="@/assets/image/nodata.png" alt="">-->
    <!--    </div>-->
  </div>
</template>

<script>
import OrderBar from '../../components/OrderBar'
import { urlParams } from '@/assets/utils'
import { form, userInfo } from '@/assets/utils/mixin'

export default {
  components: { OrderBar },
  mixins: [ userInfo, form ],
  data() {
    return {
      serviceNo: urlParams.get('serviceNo'),

      form: {
        saleServiceId: urlParams.get('saleServiceId'),
        otherCost: [],
      },
      options: {
        feePurpose: [],
      },
      rules: { required: [ { required: true } ] },

      moneyMap: {
        '101_101': 300,
        '103_105':100,
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.init()
  },
  mounted() {
  },
  methods: {
    init() {
      this.getUserInfo()
      this.getDetail()
      // this.getOtherCostOptions()
      this.getfeePurposeOptions()
    },

    async getDetail() {
      const res = await this.server.get('/saleService/getFeeListBySaleServiceId', {
        saleServiceId: this.form.saleServiceId,
      })
      if (res.code === '0') this.form.otherCost = res.object
    },

    // 其他费用 - 费用属性
    async getOtherCostOptions() {
      Promise.all([
        this.getOptionsType('105'),
        this.getOptionsType('106'),
      ]).then(res => {
        this.options.feePurpose = res.flat().map(e => ({ label: e.name, value: e.value }))
      })
    },

    async getOptionsType(parentId) {
      const res = await this.server.get('/saleService/findNoteSubFeeTypes', { parentId })
      return res
    },

    addOtherCost(item = {}) {
      this.form.otherCost.push({
        saleServiceId: this.form.saleServiceId,
        feePurpose: item.feePurpose || '',
        feePurposeName: item.feePurposeName || '',
        feeDesc: item.feeDesc || '',
        workDay: item.workDay || null,
        feeNum: item.feeNum || null,
        price: item.price || null,
        time: new Date().getTime(),
      })
    },

    removeOtherCost(index) {
      this.form.otherCost.splice(index, 1)
    },

    // 其他费用 - 费用属性
    async getfeePurposeOptions() {
      const res = await this.server.get('/saleService/findReportAllFeePurpose', {
        parentId: '103',
      })
      if (res.code === '0') {
        this.options.feePurpose = res.object.map(e => ({
          label: e.feePurposeName, value: e.feePurpose,
        }))
      }
    },

    changeCost(form) {
      form.price = this.moneyMap[form.feePurpose]
    },

    async submit(url) {
      if (this.loadingSubmit) return
      this.form.otherCost.forEach((e, i) => {
        this.rules[`otherCost.${i}.workDay`] = this.rules.required
        this.rules[`otherCost.${i}.feeNum`] = this.rules.required
        this.rules[`otherCost.${i}.price`] = this.rules.required
        this.rules[`otherCost.${i}.feeDesc`] = this.rules.required
      })

      const bol = await this.validate()
      if (!bol) return this.$toast('请填写表单')
      // 组装数据
      this.form.fees = [
        // ...this.form.mealListForm.filter(e => this.form.mealList.includes(e.feePurpose)),
        // ...this.form.costListForm.filter(e => this.form.costList.includes(e.feePurpose)),
        ...this.form.otherCost,
      ]
      this.loadingSubmit = true
      this.$toast('提交中，请勿重复提交！')

      const res = await this.server.post(url, this.form.otherCost)
      if (res.code === '0') {
        this.$toast({ message: '提交成功', duration: 1000, onClose: () => this.close() })
      } else {
        this.$toast(res.msg || res.message)
        this.loadingSubmit = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import "../../assets/var";

.container {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;

  > div {
    width: 100%;
  }

  .content {
    position: relative;
    flex: 1;
    background: #f8f8f8;

    .form {
      margin-bottom: 100px;
      width: 100%;
      min-height: calc(100% - 56px);

      .otherCost {
        background: #fff;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        padding: 0;

        .left {
          flex: 1;

          > .van-cell {
            padding: 0;
          }
        }

        .right {
          width: 40px;
          height: 80px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }

  .btns {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    margin-bottom: 30px;
    .safe-margin();
  }

  .nodata {
    margin-top: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
  }
}

</style>
